package com.lh.lepay.common;

import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.memory.ChatMemory;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

@Component
public class RedisChatMemoryStore implements ChatMemoryStore {

    private final RedisTemplate<String, String> redisTemplate;
    private static final String KEY_PREFIX = "chat:memory:";
    private static final String KEY_DATA = "chat:data:";

    //@Autowired
    public RedisChatMemoryStore(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        String key = getKey(memoryId);
        String messagesJson = redisTemplate.opsForValue().get(key);

        if (messagesJson == null || messagesJson.isEmpty()) {
            return new LinkedList<>();
        }

        return ChatMessageDeserializer.messagesFromJson(messagesJson);
    }

    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> messages) {
        String key = getKey(memoryId);
        String messagesJson = ChatMessageSerializer.messagesToJson(messages);
        //String currentTime = String.valueOf(System.currentTimeMillis()); // 或 Instant.now().toString();

        // 批量操作（非原子，但减少网络开销）
        redisTemplate.opsForValue().set(key, messagesJson);
        //redisTemplate.opsForValue().set(KEY_DATA + memoryId, currentTime);
    }

    @Override
    public void deleteMessages(Object memoryId) {
        String key = getKey(memoryId);
        redisTemplate.delete(key);
    }

    private String getKey(Object memoryId) {
        return KEY_PREFIX + memoryId.toString();
    }
}